package org.stvd.controller.oauth;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.stvd.common.security.SecurityUserHolder;
import org.stvd.common.security.support.UserDetail;
import org.stvd.service.oauth.OauthClientDetailsService;

/**
 * @title OauthAccessController
 * @describtion 授权访问控制
 * @author houzx
 * @date Apr 13, 2021
 */
@Controller
@RequestMapping("oauth")
public class OauthAccessController {

    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;
    
    @RequestMapping(value = "confirm_access")
    public String confirmAccessPageLoad(HttpServletRequest request, ModelMap map) {
        return "/oauth/ConfirmAccess.html";
    }
    
    @RequestMapping(value = "error")
    public String errorAccessPageLoad(HttpServletRequest request, ModelMap map, @RequestParam Map<String, String> parameters) {
        if(parameters.size() <= 0) {
            //不存在任何参数，展示用户在线时长，提醒用户注销登录！
            UserDetail userDetail = SecurityUserHolder.getCurrentUserDetail();
            if(userDetail!=null) {
                map.put("showLoginMessage", true);
                map.put("userName", userDetail.getUsers().getUname());
                map.put("loginTimes", (new Date().getTime() - userDetail.getLoginTime().getTime()) / 60000);
            }
        }
        else if(!parameters.containsKey(OAuth2Utils.CLIENT_ID) 
            || !parameters.containsKey(OAuth2Utils.REDIRECT_URI)){
            map.put("errorMsg", "请求不合法, client_id、redirect_uri参数异常！");
        }
        else if(!oauthClientDetailsService.hasOauthClientId(parameters.get(OAuth2Utils.CLIENT_ID))) {
            map.put("errorMsg", "client_id是无效的、过期的或已撤销的");
        }
        else if(!oauthClientDetailsService.hasOauthRedirectUri(parameters.get(OAuth2Utils.CLIENT_ID), parameters.get(OAuth2Utils.REDIRECT_URI))) {
            map.put("errorMsg", "redirect_uri不匹配");
        }
        return "/oauth/ErrorAccess.html";
    }
}
